package com.iot.auth.controller;

import com.dc3.common.bean.R;
import com.dc3.common.constant.ServiceConstant;
import com.iot.auth.pojo.Dc3User;
import com.iot.auth.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * @Author 咕唧
 * @Date 2022/7/16 14:27
 * @Version 1.0
 */
@RestController
@RequestMapping("/user")
public class UserController {

    private UserService userService;

    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    @RequestMapping("/info/{id}")
    Mono<R> findById(@PathVariable String id) {
        Mono<R> map = userService.findById(id).map(result -> R.ok(result));
        //System.err.println(map);
        return map;
    }

    @RequestMapping("/list")
    Mono<R> findByIdIn(@RequestBody List<String> ids) {
        return userService.findByIdIn(ids).collectList().map(R::ok);
    }

    @PostMapping("/adduser")
    public Mono<R<Object>> addUser(@RequestBody Mono<Dc3User> userMono, String tenantId) {
        return userService.addUser(userMono, tenantId);
    }

    @PostMapping("/login")
    public Mono<R<Object>> login(String username, String password, String tenantName, ServerWebExchange exchange) {
        return userService.login(username, password, tenantName)
                .map(jwt -> {
                    exchange.getResponse().getHeaders().add(ServiceConstant.Header.X_AUTH_TOKEN, jwt);
                    return R.ok();
                }).defaultIfEmpty(R.fail("账号密码错误"));
    }

}
